<template>
  <view>
    <!-- 地址选择 -->
    <wd-action-sheet
      v-bind="$attrs"
      title="地址管理"
      @close="emits('close')"
      custom-class="h-[60vh]"
    >
      <view class="flex justify-center">
        <wd-button class="m-0" @click="show = true">添加地址</wd-button>
      </view>
      <view v-for="item in addressStore.address" :key="item">
        <address-card
          :address="item"
          delBtn
          @del="(id) => delAddress(id)"
          @select="(id) => selectAddress(id)"
        />
      </view>
    </wd-action-sheet>

    <!-- 添加地址 -->
    <wd-action-sheet v-model="show" title="添加地址" custom-class="h-[60vh]">
      <wd-form ref="form" :model="model">
        <wd-cell-group border>
          <wd-input
            label="联系人"
            label-width="60px"
            prop="name"
            v-model="model.name"
            :rule="[{ required: true }]"
          />
          <wd-input label="手机号" label-width="60px" prop="phone" v-model="model.phone" />
          <wd-input label="省" label-width="60px" prop="province" v-model="model.province" />
          <wd-input label="市" label-width="60px" prop="city" v-model="model.city" />
          <wd-input label="区" label-width="60px" prop="district" v-model="model.district" />
          <wd-input label="详细地址" label-width="60px" prop="detail" v-model="model.detail" />
        </wd-cell-group>
        <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
        <wd-button class="mt-8" type="primary" size="small" @click="scData">测试数据</wd-button>
      </wd-form>
    </wd-action-sheet>
  </view>
</template>

<script lang="ts" setup>
import AddressCard from './address-card.vue'
import { useAddressStore } from '@/store'

const emits = defineEmits(['close'])
const props = defineProps([])

const addressStore = useAddressStore()

const show = ref(false)

const model = ref<{
  name: string
  phone: string
  province: string
  city: string
  district: string
  detail: string
}>({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
})
const form = ref()
const handleSubmit = () => {
  form.value.validate().then(({ valid, error }) => {
    if (valid) {
      addressStore.addAddress(model.value)
      show.value = false
    }
  })
}
const scData = () => {
  model.value = {
    name: '张三',
    phone: '13800138000',
    province: '广东省',
    city: '深圳市',
    district: '南山区',
    detail: '科技园',
  }
}

const delAddress = (id: number) => {
  addressStore.delAddress(id)
}

const selectAddress = (id: number) => {
  addressStore.selectAddress(id)
}
</script>

<style lang="scss" scoped>
//
</style>
